import React from 'react';
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Select,
  Row,
  Col,
  Button,
  message,
} from 'antd';
import { connect } from 'dva';
import hexSha1 from 'sha1';
import { routerRedux } from 'dva/router';
import styles from './RegistrationForm.css';

const FormItem = Form.Item;
const option = Select.Option;
const Option = option;

class RegistrationForm extends React.Component {
  state = {
    confirmDirty: false,
  };


  componentWillReceiveProps(nextProps) {
    const Result = nextProps.register.result;
    const result = Result;
    if (result.code === 0) {
      message.success(result.message, 0.8);
      setTimeout(() => (this.props.dispatch(routerRedux.push('userlogin'))),
        1000
      );
    } else if (result.code === 1) {
      message.warning(result.message);
      this.props.dispatch({
        type: 'register/clearResult',
      });
    }
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const userInfo = {
          user_name: values.user_name,
          password: hexSha1(values.password),
          tel: values.tel,
        };
        this.props.dispatch({
          type: 'register/userRegite',
          payload: {
            ...userInfo,
          },
        });
      }
    });
  }
  handleConfirmBlur = (e) => {
    const val = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!val });
  }
  compareToFirstPassword = (rule, value, callback) => {
    const useForm = this.props.form;
    if (value && value !== useForm.getFieldValue('password')) {
      callback('两次输入密码不一致!');
    } else {
      callback();
    }
  }
  validateToNextPassword = (rule, value, callback) => {
    const useForm = this.props.form;
    if (value && this.state.confirmDirty) {
      useForm.validateFields(['confirm'], { force: true });
    }
    callback();
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };
    const prefixSelector = getFieldDecorator('prefix', {
      initialValue: '86',
    })(
      <Select style={{ width: 70 }}>
        <Option value="86">+86</Option>
        <Option value="87">+87</Option>
      </Select>
    );
    return (
      <div className={styles.layout}>
        <Row type="flex" justify="center">
          <Col span={8}>
            <Form onSubmit={this.handleSubmit} className={styles.form}>
              <FormItem
                {...formItemLayout}
                label={(
                  <span>
                    昵称&nbsp;
                    <Tooltip title="What do you want others to call you?">
                      <Icon type="question-circle-o" />
                    </Tooltip>
                  </span>
                )}
              >
                {getFieldDecorator('user_name', {
                  rules: [{ required: true, message: '请输入您的用户昵称!', whitespace: true }],
                })(
                  <Input />
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="密码"
              >
                {getFieldDecorator('password', {
                  rules: [{
                    required: true, message: '请输入您的密码!',
                  }, {
                    validator: this.validateToNextPassword,
                  }],
                })(
                  <Input type="password" />
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="确认密码"
              >
                {getFieldDecorator('confirm', {
                  rules: [{
                    required: true, message: '请重新确认您的密码!',
                  }, {
                    validator: this.compareToFirstPassword,
                  }],
                })(
                  <Input type="password" onBlur={this.handleConfirmBlur} />
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="电话号码"
              >
                {getFieldDecorator('tel', {
                  rules: [{ required: true, message: '请输入您的电话号码!' }],
                })(
                  <Input addonBefore={prefixSelector} style={{ width: '100%' }} />
                )}
              </FormItem>
              <FormItem {...tailFormItemLayout}>
                <Button type="primary" htmlType="submit">Register</Button>
              </FormItem>
            </Form>
          </Col>
        </Row>
      </div>
    );
  }
}

const WrappedRegistrationForm = Form.create()(RegistrationForm);

export default connect(({ register }) => ({
  register,
}))(WrappedRegistrationForm);
